Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [58]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [59]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [60]:
import cv2                
import matplotlib.pyplot as plt    
from tqdm import tqdm
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[100])
# convert BGR image to grayscale
print('Converting to grayscale...')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

print('Finding faces...')
# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in tqdm(faces):
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Converting to grayscale...
Finding faces...
Number of faces detected: 1
100%|███████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 333.23it/s]

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [61]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

In [62]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.
from collections import Counter


cv_face_detector_results_on_human_files  = [face_detector(path) for path in tqdm(human_files_short)]
cv_face_detector_results_on_human_files_count = Counter(cv_face_detector_results_on_human_files) 
print('% of human images with detected human faces:', cv_face_detector_results_on_human_files_count[True] / len(cv_face_detector_results_on_human_files)) 

human_failed_indices = [i for i, x in enumerate(cv_face_detector_results_on_human_files) if not x]
print('Failed indices:', human_failed_indices)



cv_face_detector_results_on_dog_files  = [face_detector(path) for path in tqdm(dog_files_short)]
cv_face_detector_results_on_dog_files_count = Counter(cv_face_detector_results_on_dog_files) 
print('% of dog images with detected human faces:', cv_face_detector_results_on_dog_files_count[True] / len(cv_face_detector_results_on_dog_files))

dog_failed_indices = [i for i, x in enumerate(cv_face_detector_results_on_dog_files) if x]
print('Failed indices:', dog_failed_indices)


print('Human failed (to detect faces) image:')
for idx in human_failed_indices:
    img = cv2.imread(human_files_short[idx])
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(cv_rgb)
    plt.show()

print('Dog failed (to NOT detect faces) image:')
for idx in dog_failed_indices:
    img = cv2.imread(dog_files_short[idx])
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(cv_rgb)
    plt.show()


## on the images in human_files_short and dog_files_short.
100%|████████████████████████████████████████████████████████████████████████████████| 100/100 [00:03<00:00, 31.58it/s]
% of human images with detected human faces: 0.99
Failed indices: [0]
100%|████████████████████████████████████████████████████████████████████████████████| 100/100 [00:12<00:00,  8.14it/s]
% of dog images with detected human faces: 0.11
Failed indices: [0, 14, 15, 21, 22, 23, 24, 30, 32, 63, 78]
Human failed (to detect faces) image:
Dog failed (to NOT detect faces) image:

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

No, there are many images having partial faces, especially sometimes people are not directly looking at the camera. Just like the image shown above. CNN can helps as it can capture more complex features, given enough images.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

Human Face Detector CNN version

Steps:

  1. 3000 sample was taken form each human and dog datasets.
  2. Evaluate the base line model (OpenCV)
  3. Evaluate a CNN Human binary classifier
In [19]:
## (Optional) TODO: Report the performance of another  
features_X = np.append(human_files[:3000], train_files[:3000])

# create labels
# 0: human images, 1: not human images
labels_Y = np.append(np.zeros(human_files[:3000].shape[0]), np.ones(train_files[:3000].shape[0]))
print(features_X.shape)
print(labels_Y.shape)
(6000,)
(6000,)
In [7]:
## Base line
print('Base Line:')
cv_face_detector_results_on_human_files  = [face_detector(path) for path in tqdm(human_files[:3000])]
cv_face_detector_results_on_human_files_count = Counter(cv_face_detector_results_on_human_files) 
h_acc = cv_face_detector_results_on_human_files_count[True] / len(cv_face_detector_results_on_human_files)
print('% Accuracy on human dataset:', h_acc) 

cv_face_detector_results_on_dog_files  = [face_detector(path) for path in tqdm(train_files[:3000])]
cv_face_detector_results_on_dog_files_count = Counter(cv_face_detector_results_on_dog_files) 
d_acc = cv_face_detector_results_on_dog_files_count[False] / len(cv_face_detector_results_on_dog_files)
print('% Accuracy on dog dataset:', d_acc)
print('% Overall Base Line Accuracy:', (h_acc + d_acc) / 2)
Base Line:
100%|██████████████████████████████████████████████████████████████████████████████| 3000/3000 [01:25<00:00, 35.27it/s]
% Accuracy on human dataset: 0.9913333333333333
100%|██████████████████████████████████████████████████████████████████████████████| 3000/3000 [07:57<00:00,  6.28it/s]
% Accuracy on dog dataset: 0.882
% Overall Base Line Accuracy: 0.9366666666666666
In [20]:
## move the preprocessing code here

from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    del img
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)
In [21]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
features_X_tensors = paths_to_tensor(features_X).astype('float32') / 255

print(features_X_tensors.shape)
100%|█████████████████████████████████████████████████████████████████████████████| 6000/6000 [00:32<00:00, 186.27it/s]
(6000, 224, 224, 3)
In [22]:
from keras.utils import to_categorical
labels_Y_one_hot = to_categorical(labels_Y, 2)
print(labels_Y_one_hot.shape)
(6000, 2)
In [23]:
# get train test set for the humum detector
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle

features_X_tensors, labels_Y_one_hot = shuffle(features_X_tensors, labels_Y_one_hot, random_state=42)
human_detector_X_train, human_detector_X_test, human_detector_y_train, human_detector_y_test = train_test_split(features_X_tensors, labels_Y_one_hot, test_size=0.3, random_state=42)

print(human_detector_X_train.shape)
print(human_detector_X_test.shape)
(4200, 224, 224, 3)
(1800, 224, 224, 3)
In [24]:
from keras.layers import Dropout, Flatten, Dense
from keras.layers import Conv2D, MaxPooling2D
from keras.models import Sequential
from keras.models import load_model
from keras.callbacks import ModelCheckpoint  

model = Sequential()

model.add(Conv2D(8, 
                 kernel_size=(3, 3), 
                 activation='relu',
                 input_shape=(224, 224, 3)))

model.add(Conv2D(8, 
                 kernel_size=(3, 3), 
                 activation='relu'))
          
model.add(MaxPooling2D(pool_size=(2, 2)))
          
model.add(Conv2D(16,
                 kernel_size=(3, 3), 
                 activation='relu'))    

model.add(Conv2D(16,
                 kernel_size=(3, 3), 
                 activation='relu'))
          
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32,
                 kernel_size=(3, 3), 
                 activation='relu'))    

model.add(Conv2D(32,
                 kernel_size=(3, 3), 
                 activation='relu'))
          
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())  
model.add(Dense(2000, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1000, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2,  activation='softmax'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_7 (Conv2D)            (None, 222, 222, 8)       224       
_________________________________________________________________
conv2d_8 (Conv2D)            (None, 220, 220, 8)       584       
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 110, 110, 8)       0         
_________________________________________________________________
conv2d_9 (Conv2D)            (None, 108, 108, 16)      1168      
_________________________________________________________________
conv2d_10 (Conv2D)           (None, 106, 106, 16)      2320      
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 53, 53, 16)        0         
_________________________________________________________________
conv2d_11 (Conv2D)           (None, 51, 51, 32)        4640      
_________________________________________________________________
conv2d_12 (Conv2D)           (None, 49, 49, 32)        9248      
_________________________________________________________________
max_pooling2d_7 (MaxPooling2 (None, 24, 24, 32)        0         
_________________________________________________________________
flatten_3 (Flatten)          (None, 18432)             0         
_________________________________________________________________
dense_4 (Dense)              (None, 2000)              36866000  
_________________________________________________________________
dropout_3 (Dropout)          (None, 2000)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 1000)              2001000   
_________________________________________________________________
dropout_4 (Dropout)          (None, 1000)              0         
_________________________________________________________________
dense_6 (Dense)              (None, 2)                 2002      
=================================================================
Total params: 38,887,186
Trainable params: 38,887,186
Non-trainable params: 0
_________________________________________________________________
In [25]:
checkpointer = ModelCheckpoint(filepath='saved_models/best_human_detector.hdf5', 
                               verbose=1, save_best_only=True)

history = model.fit(human_detector_X_train, human_detector_y_train,
          batch_size=10,
          epochs=5,
          verbose=2,
          callbacks=[checkpointer],
          validation_data=(human_detector_X_test, human_detector_y_test))

del model
Train on 4200 samples, validate on 1800 samples
Epoch 1/5
Epoch 00000: val_loss improved from inf to 0.11584, saving model to saved_models/best_human_detector.hdf5
30s - loss: 0.2035 - acc: 0.9276 - val_loss: 0.1158 - val_acc: 0.9700
Epoch 2/5
Epoch 00001: val_loss improved from 0.11584 to 0.05612, saving model to saved_models/best_human_detector.hdf5
30s - loss: 0.0852 - acc: 0.9750 - val_loss: 0.0561 - val_acc: 0.9856
Epoch 3/5
Epoch 00002: val_loss improved from 0.05612 to 0.04586, saving model to saved_models/best_human_detector.hdf5
28s - loss: 0.0443 - acc: 0.9850 - val_loss: 0.0459 - val_acc: 0.9889
Epoch 4/5
Epoch 00003: val_loss did not improve
27s - loss: 0.0660 - acc: 0.9817 - val_loss: 0.0610 - val_acc: 0.9867
Epoch 5/5
Epoch 00004: val_loss did not improve
27s - loss: 0.0397 - acc: 0.9871 - val_loss: 0.0744 - val_acc: 0.9839
In [26]:
model = load_model('saved_models/best_human_detector.hdf5')
score = model.evaluate(human_detector_X_test, human_detector_y_test, verbose=0)
print(score[1])
0.988888888889
In [27]:
from sklearn.metrics import confusion_matrix
from numpy import argmax

human_detector_y_pred = model.predict(human_detector_X_test)

cm = confusion_matrix(argmax(human_detector_y_test, axis=1), argmax(human_detector_y_pred, axis=1))
# 0: human images, 1: not human images
print(cm)
print('Accuracy on Human Dataset:', cm[0][0] / (cm[0][0] + cm[1][0]))
print('Accuracy on Dog Dataset:', cm[1][1] / (cm[0][1] + cm[1][1]))
[[903  10]
 [ 10 877]]
Accuracy on Human Dataset: 0.989047097481
Accuracy on Dog Dataset: 0.988726042841

Human Face Dector Models Comparison:

Overall Accuracy Accuracy on Human Dataset Accuracy on Dog Dataset
OpenCV 0.936666 0.9913333333333333 0.882
CNN 0.988888888889 0.989047097481 0.988726042841

A simple CNN model performs much better than the OpenCV one.


Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [28]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [29]:
## code moved above for human classification

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [30]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [31]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [20]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
ResNet50_prediction_on_human = [dog_detector(img) for img in tqdm(human_files_short)]
ResNet50_prediction_on_human_count = Counter(ResNet50_prediction_on_human) 
print('% images in human_files_short have a detected dog')
print(ResNet50_prediction_on_human_count[True] / len(ResNet50_prediction_on_human))

ResNet50_prediction_on_dog = [dog_detector(img) for img in tqdm(dog_files_short)]
ResNet50_prediction_on_dog_count = Counter(ResNet50_prediction_on_dog) 
print('% images in dog_files_short have a detected dog')
print(ResNet50_prediction_on_dog_count[True] / len(ResNet50_prediction_on_dog))
100%|████████████████████████████████████████████████████████████████████████████████| 100/100 [00:03<00:00, 38.20it/s]
% images in human_files_short have a detected dog
0.01
100%|████████████████████████████████████████████████████████████████████████████████| 100/100 [00:03<00:00, 31.54it/s]
% images in dog_files_short have a detected dog
1.0

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [21]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|█████████████████████████████████████████████████████████████████████████████| 6680/6680 [01:00<00:00, 110.68it/s]
100%|███████████████████████████████████████████████████████████████████████████████| 835/835 [00:07<00:00, 115.84it/s]
100%|███████████████████████████████████████████████████████████████████████████████| 836/836 [00:06<00:00, 119.82it/s]
In [22]:
print(train_tensors.shape)
print(train_targets.shape)
print(valid_tensors.shape)
print(valid_targets.shape)
print(test_tensors.shape)
print(test_targets.shape)
(6680, 224, 224, 3)
(6680, 133)
(835, 224, 224, 3)
(835, 133)
(836, 224, 224, 3)
(836, 133)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

It is a common CNN architecture to have multiple Conv. blocks and a fully connected layers at the end (VGG).
Steps:

  1. I first tried the suggested architecture, see the baseline performance.

  2. Then I tuned the filter sizes because adding complexing to the model may help.

  3. Since the model still perform pooly and there is no sign of overfitting, I reduced at the dropout rates.

  4. After all, the result is stll ~ 1%

In [37]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

model.add(Conv2D(16, 
                 kernel_size=(3, 3), 
                 activation='relu',
                 padding='same',
                 input_shape=(224, 224, 3)))
model.add(Conv2D(16, 
                 kernel_size=(3, 3), 
                 padding='same',
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.1))
model.add(Conv2D(32,
                 kernel_size=(3, 3), 
                 padding='same',
                 activation='relu'))    
model.add(Conv2D(32,
                 kernel_size=(3, 3), 
                 padding='same',
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.1))
model.add(Conv2D(64,
                 kernel_size=(3, 3), 
                 padding='same',
                 activation='relu'))
model.add(Conv2D(64,
                 kernel_size=(3, 3), 
                 padding='same',
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.1))
model.add(GlobalAveragePooling2D())

model.add(Dense(128, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(133,  activation='softmax'))


model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_13 (Conv2D)           (None, 224, 224, 16)      448       
_________________________________________________________________
conv2d_14 (Conv2D)           (None, 224, 224, 16)      2320      
_________________________________________________________________
max_pooling2d_9 (MaxPooling2 (None, 112, 112, 16)      0         
_________________________________________________________________
dropout_5 (Dropout)          (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_15 (Conv2D)           (None, 112, 112, 32)      4640      
_________________________________________________________________
conv2d_16 (Conv2D)           (None, 112, 112, 32)      9248      
_________________________________________________________________
max_pooling2d_10 (MaxPooling (None, 56, 56, 32)        0         
_________________________________________________________________
dropout_6 (Dropout)          (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_17 (Conv2D)           (None, 56, 56, 64)        18496     
_________________________________________________________________
conv2d_18 (Conv2D)           (None, 56, 56, 64)        36928     
_________________________________________________________________
max_pooling2d_11 (MaxPooling (None, 28, 28, 64)        0         
_________________________________________________________________
dropout_7 (Dropout)          (None, 28, 28, 64)        0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 64)                0         
_________________________________________________________________
dense_7 (Dense)              (None, 128)               8320      
_________________________________________________________________
dropout_8 (Dropout)          (None, 128)               0         
_________________________________________________________________
dense_8 (Dense)              (None, 133)               17157     
=================================================================
Total params: 97,557
Trainable params: 97,557
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [24]:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [25]:
from keras.callbacks import ModelCheckpoint  
from keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(
        rotation_range=40,
        width_shift_range=0.2,
        height_shift_range=0.2,
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True,
        fill_mode='nearest')

datagen.fit(train_tensors)



epochs = 5
batch_size = 20


checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=2, save_best_only=True)

model.fit_generator(datagen.flow(train_tensors, train_targets, batch_size=batch_size),
                    validation_data = datagen.flow(valid_tensors, valid_targets, batch_size=batch_size),
                    steps_per_epoch=len(train_tensors) / batch_size,
                    validation_steps=len(valid_tensors) / batch_size,
                    epochs=epochs,
                    callbacks=[checkpointer],
                    verbose=2
                   )

# from keras.callbacks import ModelCheckpoint  

# epochs = 5

# ### Do NOT modify the code below this line.

# checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
#                                verbose=1, save_best_only=True)

# model.fit(train_tensors, train_targets, 
#           validation_data=(valid_tensors, valid_targets),
#           epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=2)
Epoch 1/5
Epoch 00000: val_loss improved from inf to 4.87451, saving model to saved_models/weights.best.from_scratch.hdf5
78s - loss: 4.8858 - acc: 0.0075 - val_loss: 4.8745 - val_acc: 0.0108
Epoch 2/5
Epoch 00001: val_loss improved from 4.87451 to 4.87009, saving model to saved_models/weights.best.from_scratch.hdf5
77s - loss: 4.8733 - acc: 0.0099 - val_loss: 4.8701 - val_acc: 0.0108
Epoch 3/5
Epoch 00002: val_loss did not improve
76s - loss: 4.8700 - acc: 0.0084 - val_loss: 4.8701 - val_acc: 0.0096
Epoch 4/5
Epoch 00003: val_loss improved from 4.87009 to 4.86867, saving model to saved_models/weights.best.from_scratch.hdf5
76s - loss: 4.8679 - acc: 0.0102 - val_loss: 4.8687 - val_acc: 0.0108
Epoch 5/5
Epoch 00004: val_loss did not improve
74s - loss: 4.8676 - acc: 0.0114 - val_loss: 4.8710 - val_acc: 0.0120
Out[25]:
<keras.callbacks.History at 0x1daab766470>

Load the Model with the Best Validation Loss

In [26]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [27]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 1.1962%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [63]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [64]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_5 ( (None, 512)               0         
_________________________________________________________________
dense_14 (Dense)             (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [65]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [66]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=2)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
Epoch 00000: val_loss improved from inf to 10.41166, saving model to saved_models/weights.best.VGG16.hdf5
13s - loss: 12.0291 - acc: 0.1368 - val_loss: 10.4117 - val_acc: 0.2240
Epoch 2/20
Epoch 00001: val_loss improved from 10.41166 to 9.84741, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 9.8384 - acc: 0.3013 - val_loss: 9.8474 - val_acc: 0.2922
Epoch 3/20
Epoch 00002: val_loss improved from 9.84741 to 9.69586, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 9.3850 - acc: 0.3587 - val_loss: 9.6959 - val_acc: 0.3102
Epoch 4/20
Epoch 00003: val_loss improved from 9.69586 to 9.43655, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 9.0835 - acc: 0.3906 - val_loss: 9.4366 - val_acc: 0.3305
Epoch 5/20
Epoch 00004: val_loss improved from 9.43655 to 9.32307, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 8.9127 - acc: 0.4133 - val_loss: 9.3231 - val_acc: 0.3497
Epoch 6/20
Epoch 00005: val_loss improved from 9.32307 to 9.27877, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 8.8322 - acc: 0.4247 - val_loss: 9.2788 - val_acc: 0.3401
Epoch 7/20
Epoch 00006: val_loss improved from 9.27877 to 9.22987, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 8.7247 - acc: 0.4361 - val_loss: 9.2299 - val_acc: 0.3557
Epoch 8/20
Epoch 00007: val_loss did not improve
3s - loss: 8.6848 - acc: 0.4484 - val_loss: 9.2859 - val_acc: 0.3545
Epoch 9/20
Epoch 00008: val_loss improved from 9.22987 to 8.97800, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 8.6468 - acc: 0.4487 - val_loss: 8.9780 - val_acc: 0.3784
Epoch 10/20
Epoch 00009: val_loss improved from 8.97800 to 8.83747, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 8.3585 - acc: 0.4654 - val_loss: 8.8375 - val_acc: 0.3844
Epoch 11/20
Epoch 00010: val_loss improved from 8.83747 to 8.75003, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 8.2924 - acc: 0.4769 - val_loss: 8.7500 - val_acc: 0.3892
Epoch 12/20
Epoch 00011: val_loss improved from 8.75003 to 8.70404, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 8.1505 - acc: 0.4807 - val_loss: 8.7040 - val_acc: 0.3976
Epoch 13/20
Epoch 00012: val_loss improved from 8.70404 to 8.67336, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 8.0672 - acc: 0.4883 - val_loss: 8.6734 - val_acc: 0.3916
Epoch 14/20
Epoch 00013: val_loss improved from 8.67336 to 8.53672, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 7.9681 - acc: 0.4927 - val_loss: 8.5367 - val_acc: 0.4108
Epoch 15/20
Epoch 00014: val_loss did not improve
3s - loss: 7.9307 - acc: 0.5013 - val_loss: 8.5674 - val_acc: 0.4024
Epoch 16/20
Epoch 00015: val_loss improved from 8.53672 to 8.44822, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 7.8816 - acc: 0.5018 - val_loss: 8.4482 - val_acc: 0.4180
Epoch 17/20
Epoch 00016: val_loss improved from 8.44822 to 8.27723, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 7.7983 - acc: 0.5081 - val_loss: 8.2772 - val_acc: 0.4311
Epoch 18/20
Epoch 00017: val_loss did not improve
4s - loss: 7.7093 - acc: 0.5147 - val_loss: 8.3069 - val_acc: 0.4275
Epoch 19/20
Epoch 00018: val_loss improved from 8.27723 to 8.17101, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 7.6052 - acc: 0.5129 - val_loss: 8.1710 - val_acc: 0.4156
Epoch 20/20
Epoch 00019: val_loss improved from 8.17101 to 8.04844, saving model to saved_models/weights.best.VGG16.hdf5
4s - loss: 7.4674 - acc: 0.5201 - val_loss: 8.0484 - val_acc: 0.4371
Out[66]:
<keras.callbacks.History at 0x2166fb89e48>

Load the Model with the Best Validation Loss

In [67]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [68]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 41.7464%

Predict Dog Breed with the Model

In [69]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [70]:
bottleneck_features = np.load('bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']
valid_Xception = bottleneck_features['valid']
test_Xception = bottleneck_features['test']

print(train_Xception.shape[1:])
(7, 7, 2048)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

Basically, a CNN can be divided into 2 parts the features extractor and the classifier. The features extractor produces deep features of a given input. The classifier classifies output based on the deep features. In this case, The prestrained Xception data is essentially some features produced by the pre-trained CNN features extractor.

  1. I tried all bottleneck-features one by one and found the Xception is the best to go.
  2. I tried to add more dense layers to increase the complexity to try to get better result.
  3. There is a sign of overfitting (train acc >>> val. acc), therefore I added dropout layers.
  4. I then reduced the dropout rate as the testing acc. was lower after adding dropouts.
  5. After all, the testing accuracy didn't increase too much, I switched it back to the simplest model with 1 output softmax layer and a dropout layer, as it is the fastest model and also produces a reasonable performance.
In [114]:
Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
Xception_model.add(Dropout(0.3))
Xception_model.add(Dense(133, activation='softmax'))

Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_17  (None, 2048)              0         
_________________________________________________________________
dropout_31 (Dropout)         (None, 2048)              0         
_________________________________________________________________
dense_35 (Dense)             (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [116]:
Xception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [117]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
                               verbose=1, save_best_only=True)

Xception_model.fit(train_Xception, train_targets, 
          validation_data=(valid_Xception, valid_targets),
          epochs=20, batch_size=64, callbacks=[checkpointer], verbose=2)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
Epoch 00000: val_loss improved from inf to 0.61348, saving model to saved_models/weights.best.Xception.hdf5
14s - loss: 1.5432 - acc: 0.6687 - val_loss: 0.6135 - val_acc: 0.8108
Epoch 2/20
Epoch 00001: val_loss improved from 0.61348 to 0.49060, saving model to saved_models/weights.best.Xception.hdf5
4s - loss: 0.4761 - acc: 0.8594 - val_loss: 0.4906 - val_acc: 0.8539
Epoch 3/20
Epoch 00002: val_loss improved from 0.49060 to 0.44582, saving model to saved_models/weights.best.Xception.hdf5
4s - loss: 0.3573 - acc: 0.8894 - val_loss: 0.4458 - val_acc: 0.8491
Epoch 4/20
Epoch 00003: val_loss did not improve
4s - loss: 0.3043 - acc: 0.9054 - val_loss: 0.4570 - val_acc: 0.8443
Epoch 5/20
Epoch 00004: val_loss did not improve
4s - loss: 0.2627 - acc: 0.9148 - val_loss: 0.4678 - val_acc: 0.8587
Epoch 6/20
Epoch 00005: val_loss did not improve
4s - loss: 0.2303 - acc: 0.9253 - val_loss: 0.4525 - val_acc: 0.8587
Epoch 7/20
Epoch 00006: val_loss improved from 0.44582 to 0.44515, saving model to saved_models/weights.best.Xception.hdf5
4s - loss: 0.2088 - acc: 0.9344 - val_loss: 0.4451 - val_acc: 0.8551
Epoch 8/20
Epoch 00007: val_loss did not improve
4s - loss: 0.1877 - acc: 0.9400 - val_loss: 0.4548 - val_acc: 0.8527
Epoch 9/20
Epoch 00008: val_loss did not improve
4s - loss: 0.1716 - acc: 0.9455 - val_loss: 0.4643 - val_acc: 0.8563
Epoch 10/20
Epoch 00009: val_loss did not improve
4s - loss: 0.1519 - acc: 0.9518 - val_loss: 0.4645 - val_acc: 0.8563
Epoch 11/20
Epoch 00010: val_loss did not improve
4s - loss: 0.1446 - acc: 0.9539 - val_loss: 0.4677 - val_acc: 0.8635
Epoch 12/20
Epoch 00011: val_loss did not improve
4s - loss: 0.1322 - acc: 0.9570 - val_loss: 0.4660 - val_acc: 0.8599
Epoch 13/20
Epoch 00012: val_loss did not improve
4s - loss: 0.1177 - acc: 0.9617 - val_loss: 0.4787 - val_acc: 0.8587
Epoch 14/20
Epoch 00013: val_loss did not improve
4s - loss: 0.1102 - acc: 0.9668 - val_loss: 0.4879 - val_acc: 0.8587
Epoch 15/20
Epoch 00014: val_loss did not improve
4s - loss: 0.1033 - acc: 0.9657 - val_loss: 0.5013 - val_acc: 0.8659
Epoch 16/20
Epoch 00015: val_loss did not improve
4s - loss: 0.0944 - acc: 0.9729 - val_loss: 0.5085 - val_acc: 0.8575
Epoch 17/20
Epoch 00016: val_loss did not improve
4s - loss: 0.0879 - acc: 0.9734 - val_loss: 0.5160 - val_acc: 0.8551
Epoch 18/20
Epoch 00017: val_loss did not improve
4s - loss: 0.0830 - acc: 0.9740 - val_loss: 0.5251 - val_acc: 0.8539
Epoch 19/20
Epoch 00018: val_loss did not improve
4s - loss: 0.0800 - acc: 0.9751 - val_loss: 0.5391 - val_acc: 0.8587
Epoch 20/20
Epoch 00019: val_loss did not improve
4s - loss: 0.0764 - acc: 0.9762 - val_loss: 0.5183 - val_acc: 0.8563
Out[117]:
<keras.callbacks.History at 0x216914635f8>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [118]:
Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [119]:
# get index of predicted dog breed for each image in test set
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 84.3301%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [43]:
def Xception_predict_breed(img_path):
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    predicted_vector = Xception_model.predict(bottleneck_feature)
    return dog_names[np.argmax(predicted_vector)]

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [44]:
def final_detector(img_path):
    is_human = face_detector(img_path)
    is_dog = dog_detector(img_path)
    breed = Xception_predict_breed(img_path)
    plt.imshow(cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB))
    plt.show()
    if is_human:
        print('hello, human!', 'You look like a...', breed)
    elif is_dog:
        print('hello, dog!', 'You look like a...', breed)
    else:
        print('Not human nor dog.')
        

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

In [47]:
for i in range(1,13):
    final_detector('images/'+str(i)+'.jpg')
Not human nor dog.
hello, human! You look like a... Australian_shepherd
Not human nor dog.
Not human nor dog.
Not human nor dog.
hello, dog! You look like a... Australian_shepherd
hello, dog! You look like a... French_bulldog
Not human nor dog.
Not human nor dog.
hello, dog! You look like a... Beagle
hello, dog! You look like a... Bernese_mountain_dog
hello, dog! You look like a... Alaskan_malamute

The result is worse than I expect. There is a clear weakness: The face detector failed to dectect a human wearing sun glasses. The dog detector is ok for detecting dog, but the dog breed detector is not peforming well.

Improvement:

  1. The human face detector is too weak. Although my CNN trained in the optional task perform better than the OpenCV face detector, it is still not general enough as it was trained on only human and dog datasets (It is performing human vs dog classification, but not human vs non-human). Therefore, a larger group of image dataset is needed for training a generic human detector.

  2. Currently we perform multi-classes classification on the dog breeds, it force the model pick one and only one breed for the given image. If we want to say which dog breed look like a particular human face, N binary classifier for N dog breeds can be better, because it is more open-ended we don't need to get a single anwser.

  3. There are many pre-trained CNNs above, using ensemble learning and let them vote may increase the performce.

In [ ]: